/**
 * KML数据模型
 */
import LayerModel from "../LayerModel";
import store from '@/store/store';

export default class KmlLayerModel extends LayerModel {

  constructor(layerInfo){
    super(layerInfo);
  }

  // 添加KML图层
  addLayer(){

    let url = this.layerInfo.url;

    // 判断服务是否已经加载
    if(store.state.viewerLayers[url]) {
      console.error(`KmlLayerModel添加图层错误，原因：该图层已经存在。url = ${url}。`);
    }

    let prosime = viewer.dataSources.add(Cesium.KmlDataSource.load(url, {
      camera: scene.camera,
      canvas: scene.canvas
    }));

    prosime.then(dataSource => {

      // let entities = dataSource.entities.values;
      // console.log(`entities`, entities);
      // let visibleDistanceMax = this.layerInfo.visibleDistanceMax;
      //
      // for(let entity of entities) {
      //   // 最大可见距离
      //   if(visibleDistanceMax) {
      //     entity.billboard.distanceDisplayCondition = new Cesium.DistanceDisplayCondition(0, visibleDistanceMax);
      //   }
      // }

      // 保存当前图层对象到模型
      this.childLayer = dataSource;

      // 将对象添加到图层列表中
      store.state.viewerLayers[url] = this;

    }).otherwise( errInfo => {
      console.error(`KmlLayerModel添加图层错误，url = ${url}。原因：${errInfo}。`);
    });

  }

  // 飞行到指定图层
  flyTo(){

    // 经纬度坐标定位
    let isFly = super.flyTo(); // 调用父类的飞行方法：经纬度坐标定位、笛卡三维笛卡尔坐标定位

    // 没有在配置文件中定义坐标位置坐标
    if(!isFly) {

      let dataSource = this.childLayer;
      if(!!dataSource) {
        viewer.flyTo(dataSource);
      }
    }

  }

  // 设置图层的可见性
  setVisible(isVisible){

    let dataSource = this.childLayer;
    if(dataSource) {
      dataSource.show = isVisible;
    }
  }

  // 删除图层
  removeLayer(){

    let dataSource = this.childLayer;
    if(dataSource) {
      viewer.dataSources.remove(dataSource, true);
    }

    let url = this.layerInfo.url;
    if(store.state.viewerLayers[url]) {
      store.state.viewerLayers[url] = undefined;
      delete store.state.viewerLayers[url];
    }

    return true;
  }
}

export {
  KmlLayerModel
}
